package vn.demand.dragon.view
{
	import flash.events.Event;
	
	import org.puremvc.as3.interfaces.INotification;
	import org.puremvc.as3.patterns.mediator.Mediator;
	
	import vn.demand.dragon.MarketingApplicationFacade;
	import vn.demand.dragon.model.MasterdataProxy;
	import vn.demand.dragon.model.SupplierProxy;
	import vn.demand.dragon.view.components.SupplierSearch;
	
	public class SupplierSearchMediator extends Mediator
	{
		public static const NAME:String = "SupplierSearchMediator";
		
		private var masterdataProxy:MasterdataProxy;
		private var supplierProxy:SupplierProxy;
		
		private var viewCreated:Boolean = false;
		
		public function SupplierSearchMediator(mediatorId:String, view:Object)
		{
			super(mediatorId, view);
			
			masterdataProxy = facade.retrieveProxy(MasterdataProxy.NAME) as MasterdataProxy;
			supplierProxy = facade.retrieveProxy(SupplierProxy.NAME) as SupplierProxy;
			
			searchForm.addEventListener('viewCreated', onViewCreated);
			searchForm.addEventListener('onSearch', onSearch);
			searchForm.addEventListener('onReset', onReset);
		}
		
		public function onViewCreated(event:Event):void {
			viewCreated = true;
			if (masterdataProxy.masterdataLoaded) {
				prepareData();
			}
		}
		 
		public function prepareData():void {
			searchForm.type.dataProvider = masterdataProxy.supplierTypesDP;
			
			RIALogger.debug(this, searchForm.type.dataProvider.toString());
			
			searchForm.type.selectedIndex = 0;
		} 
		
		public function onSearch(event:Event):void {
			var o:Object = {};
			o.type = searchForm.type.selectedData;
            
            o.code = searchForm.code.text;
            
            supplierProxy.search(o);
		}
		
		public function onReset(event:Event):void {
			searchForm.type.selectedIndex = 0;
			searchForm.code.text = '';
			
			supplierProxy.search();
		}
		
		override public function listNotificationInterests():Array 
        {
            return [ MarketingApplicationFacade.LOAD_MASTERDATA_SUCCESS,   
            ];
        }
        
        override public function handleNotification( note:INotification ):void 
        {
            switch ( note.getName() ) 
			{
				case MarketingApplicationFacade.LOAD_MASTERDATA_SUCCESS:
					onViewCreated(null);
					break;
			}
        }
		
		public function get searchForm():SupplierSearch {
			return viewComponent as SupplierSearch;
		}

	}
}